<template>
  <!-- 定位loading -->
  <van-loading color="#fff" vertical type="spinner" v-if="showLoading" class="loading">定位ing...</van-loading>
  <van-nav-bar :title="'当前城市 - ' + cityName" @click-left="onClickLeft">
    <template #left>
      <van-icon name="cross" size="24" />
    </template>
  </van-nav-bar>


  <van-search background="#f4f4f4" v-model="searchValue" placeholder="请输入城市名或者拼音" @update:model-value="onSearch"
    :show-action="showCancelButton" @focus="onFocus" :clearable="isClearable" clear-trigger="always" @clear="onClear">
    <template #action>
      <div @click="onCancel">取消</div>
    </template>
  </van-search>


  <MatchedCity :filteredCities="filteredCities" v-show="filteredCities.length > 0"></MatchedCity>


  <div class="recommend" v-show="!filteredCities.length > 0">
    <div class="gps">
      <div class="title">
        GPS定位你所在的城市
      </div>
      <van-row>
        <van-col span="11" class="city-item" v-if="cityName">{{ cityName }}</van-col>
        <van-col span="11" class="city-item" v-else>定位失败</van-col>
      </van-row>
    </div>

    <div class="hot-cities">
      <div class="title">
        热门城市
      </div>
      <van-row :gutter="[0, 5]" justify="space-around" class="hot-city" wrap>
        <van-col span="11" class="city-item" v-for="city in hotCities" :key="city.cityId"
          @click="onHotCityClick(city)">{{
            city.name }}</van-col>

      </van-row>
    </div>
  </div>

  <IndexBar :Cities="dictCities" v-show="!filteredCities.length > 0" />

</template>
<script setup>
import IndexBar from '@/components/IndexBar.vue';

import { showDialog } from 'vant';
import { ref, onMounted, computed } from "vue";
import { useStore } from "@/stores/index.js";
import { useRouter } from 'vue-router'
import { getCitiesInfo } from "@/api/index.js";
import { locationCityName } from '@/api/tool.js';
import MatchedCity from '@/components/MatchedCity.vue';
const router = useRouter()
const store = useStore();

const searchValue = ref('');
const isClearable = ref(true);
const showCancelButton = ref(false)

const cityName = computed(() => {
  if (store.cityName === "定位失败") {
    return ""
  } else {
    return store.cityName
  }
})


const showLoading = ref(false);
const hotCities = ref([]) //热门城市
const dictCities = ref([]) //城市分组列表
const filteredCities = ref([]) //搜索结果列表

//定位城市
const locateCity = async () => {

  // 显示loading 提示
  showLoading.value = true;
  const response = await getCitiesInfo()
  const { cities } = response.data; //全国城市信息

  // 获取当前热门城市
  hotCities.value = cities.filter(city => city.isHot === 1);
  // 城市分组列表
  dictCities.value = cities.sort((a, b) => a.pinyin.localeCompare(b.pinyin));


  await locationCityName() //根据当前IP 获取当前城市名称

  //根据当前城市名称，查询并设置对应的城市ID
  let found = cities.some(city => {
    //如果匹配到当前城市名称，则设置当前城市ID
    if (city.name === store.cityName) {
      store.setCityId(city.cityId)
      showLoading.value = false;
      return true; // 跳出循环
    }
  })
  if (!found) {
    //如果 没有匹配到当前城市名称
    showLoading.value = false;
  }
}


onMounted(async () => {
  await locateCity()
  // window.scrollTo(0, 0);

})
const onClickLeft = () => {
  //路由返回到首页
  if (store.cityName != "定位失败") {
    // store.setPageNum(1)
    // store.setTabIndex(0)
    console.log("首页 当前tabindex:", store.tabIndex);
    router.push('/')
  } else {
    showDialog({ message: '请选择一个城市' });
  }

};


// const onCityClick = (cityId) => {
//   console.log("点击选择的城市", cityId)
//   router.push({ path: '/' })

// }


const onHotCityClick = (city) => {
  console.log("点击选择的热门城市", city)
  store.setCityId(city.cityId)
  store.setCityName(city.name)
  store.setPageNum(1)
  store.setTabIndex(0)
  console.log("当前选择的城市", store.cityId, store.cityName)
  router.push({ path: '/' })
}



const onFocus = () => {
  showCancelButton.value = true;
  isClearable.value = true;
  console.log('onFocus');
}
// const onBlur = () => {
//   showCancelButton.value = false;
// }
const onClear = () => {

  console.log('onClear');

}


const onCancel = () => {
  // 取消搜索，返回City页面，并保留搜索框内容
  console.log('onCancel');
  showCancelButton.value = false;
  isClearable.value = false;
};




const onSearch = () => {
  const inputValue = searchValue.value.toLowerCase();
  const matchedCities = [];

  if (inputValue) {
    for (const city of dictCities.value) {
      const pinyin = city.pinyin;
      const name = city.name;

      // 匹配拼音
      const pinyinMatch = pinyin.includes(inputValue);

      // 匹配汉字
      const nameMatch = name.includes(inputValue);

      if (pinyinMatch || nameMatch) {
        matchedCities.push(city);
      }
    }
  }

  // 更新显示的城市列表
  filteredCities.value = matchedCities;
  // console.log(filteredCities.value);
};

</script>
<style scoped>
.loading {
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 999;
  background: rgba(0, 0, 0, .7);
  padding: 15px 20px;
  border-radius: 10px;
}

.van-dialog__message {
  font-size: 15px;
}

.van-search__content.van-search__content--square {
  background: #fff !important;
}

.van-cell.van-cell--borderless.van-field.van-search__field {
  background: #fff !important;
}


.recommend {
  /* padding: 20px 0 0 10px; */
}

.gps {
  padding: 20px 0 0 10px;
  margin-bottom: 20px;
}

.gps .city-item {
  text-align: center;
  height: 30px;
  background-color: #f4f4f4;
  line-height: 30px;
  border-radius: 3px;
  box-sizing: border-box;
  /* margin-left: 10px; */
  font-size: 14px;
  color: #191a1b;
  white-space: nowrap;
}

.title {
  font-size: 13px;
  color: #797d82;
  margin-bottom: 10px;
  padding: 0 0 0 10px;
}

.hot-city {
  /* padding: 20px 0 0 0; */
}

.hot-city .city-item {
  background: #f4f4f4;
  text-align: center;
  height: 30px;
  background-color: #f4f4f4;
  line-height: 30px;
  border-radius: 3px;
  box-sizing: border-box;
  /* margin-left: 10px; */
  font-size: 14px;
  color: #191a1b;
  white-space: nowrap;
}
</style>
